import random
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import status
from user import models,userser
from rest_framework.views import APIView
from utils.tooljwt import tooljwt
from .authentication import JWTAuthentication
from utils.authentication import JWTAuthenticationss
from utils.SendMes import send_message
from utils.MyRedis import myredis
import datetime
from django.db.models  import F

import json
# Create your views here.
class UserRegister(APIView):
  def post(self,request):
    #先实例化 序列化器类
    ser=userser.SerUser(data=request.data)
    #调用序列化器类的is_valid方法
    if ser.is_valid():
      #如果验证通过，则调用序列化器类的save方法
      ser.save()
      return Response({"msg":"ok","data":ser.data,"code":status.HTTP_201_CREATED})
    else:
      return Response({"msg":"error","data":ser.errors,"code":status.HTTP_400_BAD_REQUEST})
#用户用户名和密码的登录
# class UsernameLogin(APIView):
#     def post(self,request):
#       #用户登录逻辑  用户名  密码
#       username=request.data.get("username")
#       password=request.data.get("password")
#       data=models.UserModel.objects.filter(username=username,password=password).first()
#       if data:
#         #用户名和密码同时正确 ---登录成功
#         token=tooljwt.gettoken({"id":data.id,"username":data.username})
#         return Response({"msg":"ok","data":{"id":data.id,"username":data.username,"token":token}})
#       else:
#         info=models.UserModel.objects.filter(username=username).first()
#         if info:
#           #用户名正确 密码错误
#           return Response({"msg":"密码错误"})
#         else:
#           return Response({"msg":"用户名错误"})
class UsernameLogin(APIView):
    def post(self, request):
      # 用户登录逻辑  用户名  密码
      username = request.data.get("username")
      password = request.data.get("password")
      data = models.UserModel.objects.filter(username=username).first()
      if data:
        # 用户名正确 密码错误
        if data.password == password:
          #登录成功
          token = tooljwt.gettoken({"id": data.id, "username": data.username})
          return Response({"msg":"ok","data":{"id":data.id,"username":data.username,"token":token}})
        else:
          return Response({"msg":"密码错误"})
      else:
        return Response({"msg":"用户名错误"})
class Test(APIView):
  authentication_classes = (JWTAuthentication,)
  def get(self,request):
    return Response({"msg":"ok"})

class UserCenter(APIView):
  authentication_classes = (JWTAuthenticationss,)
  def get(self,request):
    return Response({"msg":"我是会员中心"})

# class UserMessage(APIView):
#   authentication_classes = (JWTAuthenticationss,)
#   def post(self,request):
#     #添加留言  (title  userid)
#     #登录成功后  前端 就会有token 和userid
#     title = request.data.get("title")
#     userid = request.data.get("userid")
#     models.MessageModel.objects.create(title=title,userid=userid)
#     return Response({"msg":"留言成功"})



#发送验证码
class SendCode(APIView):
  #获取前端传递的手机号
  def post(self,request):
    phone = request.data.get("phone")
    #生成随机验证码
    code= str(random.randint(1000,9999))
    res=json.loads(send_message(phone,code,2))
    #将验证码保存到redis中
    if res["statusCode"]=="000000":
      #将验证码保存到redis中
      myredis.set_time_str(phone,60*2,code)
      return Response({"msg":"验证码发送成功"})
    else:
      return Response({"msg":res['statusMsg']})

#用户登录验证码
class Login(APIView):
  def createdata(self,phone,code):
    #phone前端输入的手机号  code是前端输入的验证码
    #将数据号添加到数据库  手机号不存在 但是验证码输入正确 才能入库
    mycode=myredis.get_str(phone)
    if mycode==code:
      #验证码正确
      data=models.UserModel.objects.create(phone=phone,username=phone,password="000000",email=phone+"@qq.com")
      if data:
        #登录成功  生成token
        token = tooljwt.gettoken({"id":data.id})
        return Response({"msg": "登录成功", "data": {"id": data.id, "token": token}})
      else:
        return Response({"msg": "登录失败"})
    else:
      return Response({"msg": "验证码错误"})
  def post(self,request):
    phone = request.data.get("phone")
    code = request.data.get("code")
    #验证手机是否正确
    data=models.UserModel.objects.filter(phone=phone).first()
    if data:
      #如果手机正确在从redis读取验证码
      rediscode=myredis.get_str(phone)
      if code==rediscode:
        #手动的生成一个token
        token=tooljwt.gettoken({"id":data.id})
        return Response({"msg":"登录成功","data":{"id":data.id,"token":token}})
      else:
        return Response({"msg":"验证码不正确"})
    else:
      return self.createdata(phone,code)

#eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOjQsInVzZXJuYW1lIjoiIiwiZXhwIjoxNzMwNDU5MzM1fQ.fBFw3QsvYiKLxBHnA1Yg55bDi8mhYIKC5lyGKuKvpiU
class ReLogin(APIView):
  def post(self,request):
    phone = request.data.get("phone")
    code = request.data.get("code")
    mycode=myredis.get_str(phone)
    if code==mycode:
      #走验证或者注册的逻辑
      data=models.UserModel.objects.filter(phone=phone).first()
      if not data:
        #创建
        data = models.UserModel.objects.create(phone=phone, username=phone, password="000000", email=phone + "@qq.com")
      token=tooljwt.gettoken({"id":data.id})
      return Response({"msg": "登录成功", "data": {"id": data.id, "token": token}})
    else:
      return Response({"msg":"验证码错误"})


#获取当前用户的积分以及优惠券
class UserCredit(APIView):
  authentication_classes = [JWTAuthenticationss]
  def get(self,request):
    user=request.query_params.get("user")
    data=models.UserModel.objects.filter(id=user).first()
    #拿到当前用户的优惠券信息
    #查询时间范围使用range  当前时间要在  开始时间 和结束时间之间
    # start_time lt now_time   end_time  gt now_time
    coudata=models.UserCoupon.objects.filter(user=user,isused=False,coupon__created_time__lte=datetime.datetime.now(),coupon__end_time__gte=datetime.datetime.now())
    ser=userser.UserCouponSer(coudata,many=True)

    return Response({"msg":"获取成功","data":{"credit":data.score,"tomoney":10,"coupon":ser.data}})
